package org.zjt.netty.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zjt.domain.RpcMsgProto;
import org.zjt.util.RpcContext;

import java.util.concurrent.CountDownLatch;


/**
 * Created by zhangjuntao on 2017/3/16.
 */
public class RpcClientHandler extends ChannelInboundHandlerAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(RpcClientHandler.class);
    /**
     * Creates a client-side handler.
     */
    public RpcClientHandler() {
    }



    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        LOGGER.info("Receive server response : [" + msg + "]");
        RpcMsgProto.msg req = (RpcMsgProto.msg) msg;
        String tranceId = String.format("%s:%s:%s",req.getClassName(),req.getMethodName(),req.getParam() );
        RpcContext.RPC_TRAMCE_MAP.put(tranceId,req);
        CountDownLatch c =RpcContext.RPC_TRAMCE_STATUS.get(tranceId);
        if (c != null )
            c.countDown();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}

